package listeners;

import org.antlr.v4.misc.OrderedHashMap;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

public class TestPropertyFile {
    public static class PropertyFileLoader extends PropertyFileBaseListener {
        Map<String, String> props = new OrderedHashMap<>();
        @Override
        public void exitProp(PropertyFileParser.PropContext ctx) {
            String id = ctx.ID().getText();
            String value = ctx.STRING().getText();
            props.put(id, value);
            System.out.println("exit prop");
        }
    }

    public static void main(String[] args) throws IOException {
        String inputFile = null;
        if (args.length>0) {
            inputFile = args[0];
        }
        InputStream is = System.in;
        if (inputFile != null) {
            is = new FileInputStream(inputFile);
        }
        CharStream input = CharStreams.fromStream(is);
        PropertyFileLexer lexer = new PropertyFileLexer(input);
        CommonTokenStream tokenStream = new CommonTokenStream(lexer);
        PropertyFileParser parser = new PropertyFileParser(tokenStream);
        ParseTree tree = parser.file();

        // standard antlr parse tree
        ParseTreeWalker walker = new ParseTreeWalker();
        PropertyFileLoader loader = new PropertyFileLoader();
        walker.walk(loader, tree);
        System.out.println(loader.props);
    }
}
